package com.kai.interceptor;

import com.kai.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("开始进行token校验");

        //获取token 判断token是否存在
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()){
            log.info("token不存在");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED); //设置状态码 401 表示未授权
            return false;
        }

        //判断token是否正确
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //token正确
        log.info("令牌正确, 放行");
        log.info("token校验成功");
        return true;


    }
}
